﻿using System;
using System.Globalization;
using System.Threading;
using System.Windows.Forms;
using System.ComponentModel;
using System.Resources;
using ClassLibrary;
using System.IO;
using Param = ClassLibrary.Parameters.Values;
using ControlLibrary;
using System.Diagnostics;
using System.Collections.Generic;

namespace MyGoogleMap
{
    partial class MainForm
    {
        #region Files

        private bool Save(bool saveAs)
        {
            bool RC = true;
            try
            {

                if (saveAs /*|| !File.Exists(Param.localPath_UserFile)*/)
                    newMap();

                if (string.Empty != Param.localPath_UserFileName)
                {
                    UserObject userObject= new UserObject();
                    userObject.getParameters();

                    XMLSerialisation.Save<UserObject>(Param.localPath_UserFile, userObject);

                    //Generate DataSet
                    RC = MarkerDatasetConverter.Markers_To_DataSet();

                    FileModified = false;

                    // Add to MRU
                    this.mruMenuManager.Add(Param.localPath_UserFile);
                    //this.Text = _caption;
                }
                else RC = false;
            }
            catch (Exception e)
            {
                RC = false;
                ErrorManager.WriteLog("MainForm", "Save", e);
            }
            return RC;
        }

        private bool AutoSaveDialog(out bool proceed)
        {
            bool RC = true;
            try
            {
                proceed = true;

                if (FileModified)
                {
                    string msg;
                    if (File.Exists(Param.localPath_UserFile))
                        msg = Param.RM.GetString("MB_Save1") + Param.localPath_UserFileName + Param.RM.GetString("MB_Save2");
                    else msg = Param.RM.GetString("MB_Save4");

                    DialogResult dr = MessageBox.Show(this, msg, Param.RM.GetString("MB_Save3"), MessageBoxButtons.YesNoCancel, MessageBoxIcon.Question);

                    if (dr == System.Windows.Forms.DialogResult.Yes)
                    {
                        Save(false);
                        proceed = true;
                    }
                    else if (dr == System.Windows.Forms.DialogResult.No)
                        proceed = true;

                    else if (dr == System.Windows.Forms.DialogResult.Cancel)
                        proceed = false;

                }
                return true;
            }
            catch (Exception e)
            {
                proceed = false;
                ErrorManager.WriteLog("MainForm", "AutoSaveDialog", e);
                return false;
            }
        }

        private DialogResult newMap()
        {
            try
            {
                if (saveFileDialog_MGM.ShowDialog(this) == System.Windows.Forms.DialogResult.OK)
                {
                    Param.localPath_UserFile = saveFileDialog_MGM.FileName;

                    if (!Directory.Exists(Param.localPath_Small))
                        Directory.CreateDirectory(Param.localPath_Small);

                    if (!Directory.Exists(Param.localPath_Medium))
                        Directory.CreateDirectory(Param.localPath_Medium);

                    Directory.CreateDirectory(Param.localPath_Project);
                    File.Copy(Param.localPath_GoogleMap_Base, Param.localPath_GoogleMap, true);

                    _currentMarker = new Marker();
                    Param.Categories = new System.Collections.Generic.List<string>();
                    return DialogResult.OK;
                }
                else return DialogResult.Cancel;
            }
            catch (Exception e)
            {
                ErrorManager.WriteLog("MainForm", "newProject", e);
                return DialogResult.Abort;
            }
        }

        //NEW
        private void toolStripMenuItem_New_Click(object sender, EventArgs e)
        {
            try
            {
                bool proceed;
                bool RC = AutoSaveDialog(out proceed);
                if (true == RC)
                {
                    if (proceed)
                    {
                        DialogResult dr = newMap();
                        if (dr == DialogResult.OK)
                        {
                            FileModified = false;
                            _currentMarker = null;
                            Param.MarkerList.Clear();
                            listBoxUpdateDataSource();
                            //this.Text = _caption;
                            toolStripMenuItem_Parameters.Enabled = true;
                            toolStripMenuItem_Save.Enabled = true;
                            toolStripMenuItem_Display.Enabled = true;
                            toolStripMenuItem_Publish.Enabled = true;
                            panel_Marker.Init();
                            RC = Save(false);
                            if (true == RC)
                                linkLabel_AddMarker.Enabled = true;
                            else throw new Exception("Save failed");
                        }
                        else if(dr == System.Windows.Forms.DialogResult.Abort)
                            throw new Exception("NewMap failed");
                    }
                }
                else throw new Exception("AutoSaveDialog failed");

            }
            catch (Exception ex)
            {
                ErrorManager.WriteLog("MainForm_Menu", "toolStripMenuItem_New_Click", ex, Param.RM.GetString("MenuNew_Error"));
            }
        }

        //OPEN
        private void toolStripMenuItem_Open_Click(object sender, EventArgs e)
        {
            try
            {
                bool proceed;
                bool RC = AutoSaveDialog(out proceed);

                if (true == RC)
                {
                    if (proceed)
                    {
                        if (openFileDialog_MGM.ShowDialog(this) == System.Windows.Forms.DialogResult.OK)
                        {
                            Param.localPath_UserFile = openFileDialog_MGM.FileName;
                            UserObject userObject = XMLSerialisation.Load<UserObject>(Param.localPath_UserFile);
                            userObject.setParameters();
                            linkLabel_AddMarker.Enabled = true;
                            panel_Marker.SetListCategorie(Param.Categories);
                            listBoxUpdateDataSource();

                            FileModified = false;
                            this.mruMenuManager.Add(Param.localPath_UserFile);
                            //this.Text = _caption;
                            toolStripMenuItem_Parameters.Enabled = true;
                            toolStripMenuItem_Save.Enabled = true;
                            toolStripMenuItem_Display.Enabled = true;
                            toolStripMenuItem_Publish.Enabled = true;
                        }
                    }
                }
                else throw new Exception("AutoSaveDialog failed");
            }
            catch (Exception ex)
            {
                ErrorManager.WriteLog("MainForm_Menu", "toolStripMenuItem_New_Click", ex, Param.RM.GetString("MenuOpen_Error"));
            }
        }

        //IMPORT
        private void toolStripMenuItem_Import_Click(object sender, EventArgs e)
        {

        }

        //PUBLISH
        private void toolStripMenuItem_Publish_Click(object sender, EventArgs e)
        {

            try
            {
                List<string> Upload_med = new List<string>();
                List<string> Upload_small = new List<string>();
                List<string> Upload_files = new List<string>();
                Save(false);

                foreach (Marker m in Param.MarkerList)
                {
                    if (!m.published)
                    {
                        if (null != m.Img_Small && null != m.Img_Medium)
                        {
                            Upload_small.Add(Path.Combine(Param.localPath_Small, Path.GetFileName(m.Img_Small)));
                            Upload_med.Add(Path.Combine(Param.localPath_Medium, Path.GetFileName(m.Img_Medium)));
                        }
                        else
                            throw new Exception("img small / medium undefined",new Exception(m.title));
                    }
                }

                Upload_files.Add(Param.localPath_DataSet);
                Upload_files.Add(Param.localPath_GoogleMap);

                //Form_Publish publishForm = new Form_Publish(Upload_small, Upload_med, Upload_files);
                Form_Publish publishForm = new Form_Publish(Param.MarkerList);

                if (publishForm.ShowDialog(this) == System.Windows.Forms.DialogResult.OK)
                {
                    Save(false);
                }
                else
                {
                    if (publishForm.TryAgain)
                        toolStripMenuItem_Publish_Click(null, null);
                }
            }
            catch (Exception ex)
            {
                string msg = Param.RM.GetString("MB_SmallMissing");
                ErrorManager.WriteLog("MainForm_Menu", "toolStripMenuItem_Publish_Click", ex, msg+" : "+ex.InnerException.Message );
            }
        }

        //SAVE
        private void toolStripMenuItem_Save_Click(object sender, EventArgs e)
        {
            Save(false);
        }

        //DISPLAY MAP
        private void toolStripMenuItem_Offline_Click(object sender, EventArgs e)
        {
            try
            {
                Save(false);
                Process.Start(Param.localPath_GoogleMap);
            }
            catch (Exception ex)
            {
                ErrorManager.WriteLog("MainForm_Menu", "toolStripMenuItem_Offline_Click", ex);
            }
        }

        private void toolStripMenuItem_Online_Click(object sender, EventArgs e)
        {

        }

        //MRU
        private void mruMenuManager_MruMenuItemClick(object sender, Mru.MruMenuItemClickEventArgs e)
        {
            try
            {
                bool proceed;
                bool RC = AutoSaveDialog(out proceed);
                if (true == RC)
                {
                    if (proceed)
                    {
                        if (File.Exists(e.Filename))
                        {
                            Param.localPath_UserFile = e.Filename;
                            UserObject userObject = XMLSerialisation.Load<UserObject>(Param.localPath_UserFile);
                            userObject.setParameters();

                            panel_Marker.SetListCategorie(Param.Categories);
                            linkLabel_AddMarker.Enabled = true;
                            listBoxUpdateDataSource();

                            FileModified = false;
                            //this.Text = _caption;
                            toolStripMenuItem_Parameters.Enabled = true;
                            toolStripMenuItem_Save.Enabled = true;
                            toolStripMenuItem_Display.Enabled = true;
                            toolStripMenuItem_Publish.Enabled = true;
                        }
                    }
                }
                else throw new Exception("AutoSaveDialog failed");
            }
            catch (Exception ex)
            {
                ErrorManager.WriteLog("MainForm_Menu", "mruMenuManager_MruMenuItemClick", ex, Param.RM.GetString("MenuMRU_Error"));
            }
        }

        //MRU
        private void mruMenuManager_MruMenuItemFileMissing(object sender, Mru.MruMenuItemFileMissingEventArgs e)
        {
            try
            {
                DialogResult res = MessageBox.Show(Param.RM.GetString("MenuMRU_Error1") + " '" + e.Filename + "'." + System.Environment.NewLine + Param.RM.GetString("MenuMRU_Error2"),
                Application.ProductName,
                MessageBoxButtons.YesNo,
                MessageBoxIcon.Question);

                if (res == DialogResult.Yes)
                {
                    e.RemoveFromMru = true;
                }
            }
            catch (Exception ex)
            {
                ErrorManager.WriteLog("MainForm_Menu", "mruMenuManager_MruMenuItemFileMissing", ex, Param.RM.GetString("MenuMRU_Error"));
            }
        }

        //QUIT
        private void toolStripMenuItem_Quit_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        #endregion

        #region Configuration

        #region Language

        /*bool _UserClick = false;
        private void toolStripMenuItem_English_Click(object sender, EventArgs e)
        {
            _UserClick = true;
            Thread.CurrentThread.CurrentUICulture = new CultureInfo("en-US");
            Language_check(Thread.CurrentThread.CurrentUICulture.Name);
        }

        private void toolStripMenuItem_French_Click(object sender, EventArgs e)
        {
            _UserClick = true;
            Thread.CurrentThread.CurrentUICulture = new CultureInfo("fr-FR");
            Language_check(Thread.CurrentThread.CurrentUICulture.Name);
        }

        private void Language_check(string culture)
        {
            foreach (ToolStripMenuItem item in toolStripMenuItem_Language.DropDownItems)
            {
                if ((string)item.Tag != culture)
                    item.Checked = false;
                else item.Checked = true;
            }

            if (_UserClick)
            {
                Properties.Settings.Default.Language = Thread.CurrentThread.CurrentUICulture.Name;
                Properties.Settings.Default.Save();
                UpdateUI();
            }
            
            _UserClick = false;
        }*/

        #endregion

        //Parameters
        private void toolStripMenuItem_Parameters_Click(object sender, EventArgs e)
        {
            string lang = Properties.Settings.Default.Language;

            Form_Parameters param_form = new Form_Parameters(0);
            
            if (param_form.ShowDialog(this) == System.Windows.Forms.DialogResult.OK)
            {
                listBox_Marker_SelectedIndexChanged(null, null);
                panel_Marker.SetListCategorie(Param.Categories);

                Properties.Settings.Default.Language = Param.PARAM_LANGUAGE;
                Properties.Settings.Default.Save();

                FileModified = true;
            }
        }


        #endregion

        #region ?

        private void logFileToolStripMenuItem_Click(object sender, EventArgs e)
        {
            ErrorManager.ShowLog();
        }

        private void aboutToolStripMenuItem_Click(object sender, EventArgs e)
        {
            Form_Info info = new Form_Info();
            info.ShowDialog(this);
        }

        #endregion
    }
}
